<?php
/**
 * Driver MySQL for database transaction / cambia stà frase, non è un driver
 *
 * @package trunk
 * @author Gonçalo Margalho <gsky89@gmail.com> / Daniel Bernasconi <flame05@gmail.com>
 * @copyright gfwork (C) 2009
 * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License
 * @version 1.0
 */

define( 'SQL_CACHE_DIRECTORY', './cache/sql' );


class db{

    /**
     * Object vars
     *
     * @var int $sql_function_level
     * @var int $nquery
     * @var database connection $connection
     * @var $sql_debug
     */
    private $sql_function_level = 0;
	private $nquery = 0;
	private $connection = false;
	private $sql_debug = false;





    /**
     * Create a connection with the database
     *
     * @param boolean $persistent - Set true for persistant connection
     */
    public function __construct( $persistent = false ){
        global $cfg;

        include("cfg/db.cfg.php");
        if($persistent == true)
            $this->connection = mysql_pconnect( $host, $user, $pass ) or die( mysql_error() );
        else
            $this->connection = mysql_connect( $host, $user, $pass ) or die( mysql_error() );

        // più sicurezza
        unset($host);
        unset($user);
        unset($pass);

		mysql_select_db( $db_name ) or die ( mysql_error() );
    }





    /**
     * Make a query
     *
     * @param string $query - Query to make
     * @return mixed|trigger_error|boolean
     */
    public function query( $query ){
        $this->sql_function_level++;
        $this->nquery++;

        if( $r = mysql_query( $query , $this->connection ) ){
            $this->sql_function_level = 0;
        return $r;
        }
        else
			throw new Exception($this->trace_error( $query ));
        $this->sql_function_level = 0;
	return false;
    }




    /**
     * Get last id autoincremented
     *
     * @return int
     */
	public function last_id(){ return @mysql_insert_id($this->connection); }
    /**
     * Get total number of rows in a resultSet
     * @param mixed $result
     * @return int
     */
	public function total( $result ){ return mysql_num_rows( $result ); }
    /**
     * Total queries executed
     *
     * @return int
     */
	public function nQuery(){ return $this->nquery; }
    /**
     * Close the connection with the database
     *
     * @return boolean
     */
	public function disconnect(){ return mysql_close( $this->connection ); }






    /**
     * Make a query and return an array of the first result
     * If $cache is set to true, the result gets cached
     *
     * @param string $query Query to Make$
     * @param boolean $cache
     * @return array
     */
    public function query_array( $query, $cache = false ){
	global $cfg;

		if($cache){
			if($cfg->get('sql_cache_array') == 1){

				$file = new file(SQL_CACHE_DIRECTORY . md5( $query ) . '.php');

				if( $data = $file->load_array() )
					return $data;
			}
			if($cfg->get('sql_cache_array') == 2){}
		}


        $this->sql_function_level++;
        if( $result = $this->query( $query ) ){

            $array = mysql_fetch_assoc( $result );


            if( $cache ){
				if($cfg->get('sql_cache_array') == 1)
					$file->save_array( $array );
            return $array;
			}
        }
		return false;
    }





    /**
     * If $hash is set, function deletes only the file passed.
     * Else deletes every cache file in main directory
     *
     * @param string $hash
     */
    public function delete_cache_file( $hash = false ){
        if( $hash )
			unlink( SQL_CACHE_DIRECTORY . $hash . ".php" );
        else if( $cache_files = glob( SQL_CACHE_DIRECTORY . "/*.php" ) )
			foreach( $cache_files as $file_name )
				unlink( $file_name );
    }









    /**
     * TMP
     * @param <type> $query
     * @param <type> $cache
     * @return <type>
     */
	public function query_list( $query, $cache = FALSE ){
        if( $cache AND file_exists( $file_cache = ( SQL_CACHE_DIRECTORY . "/sql_" . ( $hash = md5( $query ) ) . ".php" ) ) ){
            include_once( $file_cache );
            return $GLOBALS[ 'sql_' . $hash ];
        }

        $this->sql_function_level++;
        if( $result = $this->query( $query ) ){
            $query_list = array( );
            while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) )
            $query_list[ ] = $row;

            if( $cache ){
                $fp = fopen ( $file_cache, 'w' );
                fwrite( $fp, $query_array_string = "<?php" . "\n" . "\$GLOBALS['sql_" . $hash . "'] = " . var_export( $query_list, TRUE ) . ";" . "\n?>", strlen( $query_array_string ) );
                fclose( $fp );
                $GLOBALS[ 'ncached_query' ]++;
            }
            return $query_list;
        }
    }







    /**
     * This function make a div with the error
     *
     * @param string $query - Query who are the error.
     * @return string
     */
    private function trace_error( $query ){
        $sql_error = mysql_error();
        $debug_array = debug_backtrace();

        $error_html = "\n" .
             "<div style=\"background-color:#f8f8ff; border: 1px solid #aaaaff; padding:10px;\">" . "\n" .
             "<font size=\"-1\">error: </font><font color=red>{$sql_error}</font><br>" . "\n" .
             "<font size=\"-1\">query: </font><i>{$query}</i><br><br>" . "\n" .
             "<font size=\"-1\">backtrace: </font><br>" . "\n" .
             "	<div style=\"background-color:#ffffff; border: 1px dotted #9999ee; padding: 10px;\">" . "\n";

        for( $i = $this->sql_function_level; $i < count( $debug_array ); $i++ ){
            $error_html .= "<font size=\"-1\">file: </font>" . str_replace( $_SERVER[ 'DOCUMENT_ROOT' ], "", $debug_array[ $i ][ 'file' ] ) . "<br>" . "\n";
            if( isset( $debug_array[ $i ][ 'function' ] ) )
            $error_html .= "<font size=\"-1\">function: </font>{$debug_array[ $i ][ 'function' ]}<br>" . "\n";
            $error_html .= "<font size=\"-1\">line:</font> {$debug_array[ $i ][ 'line' ]}<br><br>" . "\n";
        }
        $error_html .= "</div></div><br>" . "\n";
        return $error_html;
    }
}
?>